package jnpf.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.model.template.TagVO;
import jnpf.model.template.relationVO;
import jnpf.service.*;
import jnpf.entity.*;
import jnpf.util.*;
import jnpf.model.entity.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.base.vo.DownloadVO;
import jnpf.config.ConfigValueUtil;

import java.io.IOException;
import java.util.stream.Collectors;

import org.springframework.web.multipart.MultipartFile;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import cn.xuyanwu.spring.file.storage.FileInfo;
import lombok.Cleanup;
import jnpf.model.visualJson.config.HeaderModel;
import jnpf.base.model.ColumnDataModel;
import jnpf.base.util.VisualUtils;
import org.springframework.transaction.annotation.Transactional;
import jnpf.entity.EntityAttributeEntity;

/**
 * entity
 *
 * @版本： V3.5
 * @版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * @作者： JNPF开发平台组
 * @日期： 2025-04-10
 */
@Slf4j
@RestController
@Tag(name = "entity", description = "example")
@RequestMapping("/api/example/Entity")
public class EntityController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private EntityService entityService;
    @Autowired
    private ThemeMangeService themeMangeService;
    @Autowired
    private EntityCategoryService entityCategoryService;
    @Autowired
    private EntityAttributeService entityAttributeService;

    @Autowired
    private TagMangeService tagMangeService;
    @Autowired
    private RelationMangeService relationMangeService;

    @Autowired
    private ConfigValueUtil configValueUtil;

    @Autowired
    private TemplateService templateService;
    @Autowired
    private RelationContentService relationContentService;
    @Autowired
    private TagRelationService tagRelationService;

    /**
     * 列表
     *
     * @return
     */
    @Operation(summary = "获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody EntityRequest dto) throws IOException {
        EntityPagination entityPagination = dto.getEntityPagination();
        List<EntityEntity> list = entityService.getList(entityPagination);

        // 收集所有的templateId用于批量查询
        Set<String> templateIds = new HashSet<>();
        for (EntityEntity entity : list) {
            if (StringUtil.isNotEmpty(entity.getTemplateId())) {
                templateIds.add(entity.getTemplateId());
            }
        }

        // 使用QueryWrapper查询模板信息
        Map<String, Map<String, Object>> templateInfoMap = new HashMap<>();
        if (!templateIds.isEmpty()) {
            QueryWrapper<TemplateEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("F_ID", templateIds);
            List<TemplateEntity> templates = templateService.list(queryWrapper);
            for (TemplateEntity template : templates) {
                Map<String, Object> info = new HashMap<>();
                info.put("name", template.getName());
                info.put("version", template.getVersion());

                templateInfoMap.put(template.getId(), info);
            }
        }

        // 主题id筛选
        String themeId = dto.getThemeId();
        //是否挂载筛选
        int isMount = dto.getIsMount();

        // 根据 themeId 进行筛选
        if (StringUtil.isNotEmpty(themeId)) {
            list = list.stream().filter(entity -> themeId.equals(entity.getThemeId())).collect(Collectors.toList());
        }

        // 根据 isMount 进行筛选
        if (isMount == 1) {
            list = list.stream().filter(entity -> StringUtil.isNotEmpty(entity.getThemeId())).collect(Collectors.toList());
        } else if (isMount == 2) {
            list = list.stream().filter(entity -> StringUtil.isEmpty(entity.getThemeId())).collect(Collectors.toList());
        }
        List<Map<String, Object>> realList = new ArrayList<>();
        for (EntityEntity entity : list) {
            Map<String, Object> entityMap = JsonUtil.entityToMap(entity);
            entityMap.put("id", entityMap.get("id"));
            //副表数据
            //子表数据
//            List<EntityCategoryEntity> entityCategoryList = entityService.getEntityCategoryList(entity.getId(), entityPagination);
//            entityMap.put("tableField107", JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(entityCategoryList)));
//            List<EntityAttributeEntity> entityAttributeList = entityService.getEntityAttributeList(entity.getId(), entityPagination);
//            entityMap.put("tableField109", JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(entityAttributeList)));

            // 添加模板信息
            if (StringUtil.isNotEmpty(entity.getTemplateId())) {
                Map<String, Object> templateInfo = templateInfoMap.get(entity.getTemplateId());
                if (templateInfo != null) {
                    entityMap.put("templateName", templateInfo.get("name"));
                    entityMap.put("templateVersion", templateInfo.get("version"));
                }
            }

            // ... existing sub-table data processing code ...
            realList.add(entityMap);
        }
        //数据转换
        realList = generaterSwapUtil.swapDataList(realList, EntityConstant.getFormData(), EntityConstant.getColumnData(), entityPagination.getModuleId(), false);
        //dataLevel缺失处理
        for (int i = 0; i < list.size(); i++) {
            EntityEntity entity = list.get(i);
            Map<String, Object> realMap = realList.get(i);
            realMap.put("dataLevel", entity.getDataLevel());
            realMap.put("number", entity.getNumber());
        }


        // 收集所有的 themeId
        Set<String> themeIds = new HashSet<>();
        for (Map<String, Object> realMap : realList) {
            if (realMap.containsKey("themeId") && realMap.get("themeId") != null) {
                themeIds.add(realMap.get("themeId").toString());
            }
        }

        // 通过 themeId 列表查询对应的主题名称
        Map<String, String> themeNameMap = themeMangeService.getThemeNamesByIds(new ArrayList<>(themeIds));

        // 为返回对象列表中的元素赋值主题名称
        for (Map<String, Object> realMap : realList) {
            if (realMap.containsKey("themeId") && realMap.get("themeId") != null) {
                String themeIdValue = realMap.get("themeId").toString();
                String themeName = themeNameMap.get(themeIdValue);
                if (themeName != null) {
                    realMap.put("themeName", themeName);
                }
            }
        }

        //返回对象
        PageListVO vo = new PageListVO();
        vo.setList(realList);
        PaginationVO page = JsonUtil.getJsonToBean(entityPagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);
    }

    /**
     * 创建
     *
     * @param entityForm
     * @return
     */
    @PostMapping("/create")
    @Operation(summary = "创建")
    public ActionResult create(@RequestBody @Valid EntityEntity entityForm) {
        String b = entityService.checkForm(entityForm, 0);
        if (StringUtil.isNotEmpty(b)) {
            return ActionResult.fail(b);
        }
        try {
            entityService.saveOrUpdate(entityForm, entityForm.getId(), true);
            entityService.saveTagAndRelation(entityForm, entityForm.getId(), "2", "2");
        } catch (Exception e) {
            return ActionResult.fail("新增数据失败");
        }
        return ActionResult.success("创建成功");
    }

    /**
     * 导出Excel
     *
     * @return
     */
    @Operation(summary = "导出Excel")
    @PostMapping("/Actions/Export")
    public ActionResult Export(@RequestBody EntityPagination entityPagination) throws IOException {
        if (StringUtil.isEmpty(entityPagination.getSelectKey())) {
            return ActionResult.fail("请选择导出字段");
        }
        List<EntityEntity> list = entityService.getList(entityPagination);
        List<Map<String, Object>> realList = new ArrayList<>();
        for (EntityEntity entity : list) {
            Map<String, Object> entityMap = JsonUtil.entityToMap(entity);
            entityMap.put("id", entityMap.get("id"));
            //副表数据
            //子表数据
            List<EntityCategoryEntity> entityCategoryList = entityService.getEntityCategoryList(entity.getId(), entityPagination);
            entityMap.put("tableField107", JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(entityCategoryList)));
            List<EntityAttributeEntity> entityAttributeList = entityService.getEntityAttributeList(entity.getId(), entityPagination);
            entityMap.put("tableField109", JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(entityAttributeList)));
            realList.add(entityMap);
        }
        //数据转换
        realList = generaterSwapUtil.swapDataList(realList, EntityConstant.getFormData(), EntityConstant.getColumnData(), entityPagination.getModuleId(), false);
        String[] keys = !StringUtil.isEmpty(entityPagination.getSelectKey()) ? entityPagination.getSelectKey() : new String[0];
        UserInfo userInfo = userProvider.get();
        DownloadVO vo = this.creatModelExcel(configValueUtil.getTemporaryFilePath(), realList, keys, userInfo);
        return ActionResult.success(vo);
    }

    /**
     * 导出表格方法
     */
    public DownloadVO creatModelExcel(String path, List<Map<String, Object>> list, String[] keys, UserInfo userInfo) {
        DownloadVO vo = DownloadVO.builder().build();
        List<ExcelExportEntity> entitys = new ArrayList<>();
        if (keys.length > 0) {
            ExcelExportEntity tableField107ExcelEntity = new ExcelExportEntity("分类", "tableField107");
            List<ExcelExportEntity> tableField107List = new ArrayList<>();
            ExcelExportEntity tableField109ExcelEntity = new ExcelExportEntity("属性和值", "tableField109");
            List<ExcelExportEntity> tableField109List = new ArrayList<>();
            for (String key : keys) {
                switch (key) {
                    case "themeId":
                        entitys.add(new ExcelExportEntity("模板id", "themeId"));
                        break;
                    case "name":
                        entitys.add(new ExcelExportEntity("实体名称", "name"));
                        break;
                    case "belongUserId":
                        entitys.add(new ExcelExportEntity("实体责任人", "belongUserId"));
                        break;
                    case "dataLevel":
                        entitys.add(new ExcelExportEntity("数据敏感等级", "dataLevel"));
                        break;
                    case "createUserId":
                        entitys.add(new ExcelExportEntity("创建用户id", "createUserId"));
                        break;
                    case "createTime":
                        entitys.add(new ExcelExportEntity("创建时间", "createTime"));
                        break;
                    case "tableField107-entityId":
                        tableField107List.add(new ExcelExportEntity("实体id", "entityId"));
                        break;
                    case "tableField107-category":
                        tableField107List.add(new ExcelExportEntity("分类名称", "category"));
                        break;
                    case "tableField109-entityId":
                        tableField109List.add(new ExcelExportEntity("实体id", "entityId"));
                        break;
                    case "tableField109-categoryId":
                        tableField109List.add(new ExcelExportEntity("分类id", "categoryId"));
                        break;
                    case "tableField109-attrName":
                        tableField109List.add(new ExcelExportEntity("属性名称", "attrName"));
                        break;
                    case "tableField109-attrValue":
                        tableField109List.add(new ExcelExportEntity("属性值", "attrValue"));
                        break;
                    default:
                        break;
                }
            }
            if (tableField107List.size() > 0) {
                tableField107ExcelEntity.setList(tableField107List);
                entitys.add(tableField107ExcelEntity);
            }
            if (tableField109List.size() > 0) {
                tableField109ExcelEntity.setList(tableField109List);
                entitys.add(tableField109ExcelEntity);
            }
        }

        ExportParams exportParams = new ExportParams(null, "表单信息");
        exportParams.setType(ExcelType.XSSF);
        try {
            @Cleanup Workbook workbook = new HSSFWorkbook();
            if (entitys.size() > 0) {
                if (list.size() == 0) {
                    list.add(new HashMap<>());
                }
                //去除空数据
                List<Map<String, Object>> dataList = new ArrayList<>();
                for (Map<String, Object> map : list) {
                    int i = 0;
                    for (String key : keys) {
                        //子表
                        if (key.toLowerCase().startsWith("tablefield")) {
                            String tableField = key.substring(0, key.indexOf("-"));
                            String field = key.substring(key.indexOf("-") + 1);
                            Object o = map.get(tableField);
                            if (o != null) {
                                List<Map<String, Object>> childList = (List<Map<String, Object>>) o;
                                for (Map<String, Object> childMap : childList) {
                                    if (childMap.get(field) != null) {
                                        i++;
                                    }
                                }
                            }
                        } else {
                            Object o = map.get(key);
                            if (o != null) {
                                i++;
                            }
                        }
                    }
                    if (i > 0) {
                        dataList.add(map);
                    }
                }
                //复杂表头-表头和数据处理
                ColumnDataModel columnDataModel = JsonUtil.getJsonToBean(EntityConstant.getColumnData(), ColumnDataModel.class);
                List<HeaderModel> complexHeaderList = columnDataModel.getComplexHeaderList();
                if (!Objects.equals(columnDataModel.getType(), 3) && !Objects.equals(columnDataModel.getType(), 5)) {
                    entitys = VisualUtils.complexHeaderHandel(entitys, complexHeaderList);
                    dataList = VisualUtils.complexHeaderDataHandel(dataList, complexHeaderList);
                }

                workbook = ExcelExportUtil.exportExcel(exportParams, entitys, dataList);
            }
            String fileName = "表单信息" + DateUtil.dateNow("yyyyMMdd") + "_" + RandomUtil.uuId() + ".xlsx";
            MultipartFile multipartFile = ExcelUtil.workbookToCommonsMultipartFile(workbook, fileName);
            String temporaryFilePath = configValueUtil.getTemporaryFilePath();
            FileInfo fileInfo = FileUploadUtils.uploadFile(multipartFile, temporaryFilePath, fileName);
            vo.setName(fileInfo.getFilename());
            vo.setUrl(UploaderUtil.uploaderFile(fileInfo.getFilename() + "#" + "Temporary") + "&name=" + fileName);
        } catch (Exception e) {
            log.error("信息导出Excel错误:{}", e.getMessage());
            e.printStackTrace();
        }
        return vo;
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/batchRemove")
    @Transactional
    @Operation(summary = "批量删除")
    public ActionResult batchRemove(@RequestBody String ids) {
        List<String> idList = JsonUtil.getJsonToList(ids, String.class);
        int i = 0;
        for (String allId : idList) {
            this.delete(allId);
            i++;
        }
        if (i == 0) {
            return ActionResult.fail("删除失败");
        }
        return ActionResult.success("删除成功");
    }

    /**
     * 编辑
     *
     * @param id
     * @param entityForm
     * @return
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新")
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid EntityEntity entityForm, @RequestParam(value = "isImport", required = false) boolean isImport) {
        entityForm.setId(id);
        if (!isImport) {
            String b = entityService.checkForm(entityForm, 1);
            if (StringUtil.isNotEmpty(b)) {
                return ActionResult.fail(b);
            }
        }
        EntityEntity entity = entityService.getInfo(id);
        if (entity != null) {
            try {
                String s = entityService.saveOrUpdate(entityForm, id, false);
                if (StringUtil.isNotEmpty(s)) {
                    return ActionResult.fail(s);
                }
                entityService.saveTagAndRelation(entityForm, entityForm.getId(), "2", "2");
            } catch (Exception e) {
                return ActionResult.fail("修改数据失败");
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Operation(summary = "删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        EntityEntity entity = entityService.getInfo(id);
        if (entity != null) {
            //主表数据删除
            entityService.delete(entity);
            QueryWrapper<EntityCategoryEntity> queryWrapperEntityCategory = new QueryWrapper<>();
            queryWrapperEntityCategory.lambda().eq(EntityCategoryEntity::getEntityId, entity.getId());
            //子表数据删除
            entityCategoryService.remove(queryWrapperEntityCategory);
            QueryWrapper<EntityAttributeEntity> queryWrapperEntityAttribute = new QueryWrapper<>();
            queryWrapperEntityAttribute.lambda().eq(EntityAttributeEntity::getEntityId, entity.getId());
            //子表数据删除
            entityAttributeService.remove(queryWrapperEntityAttribute);

            // 删除标签关联数据
            QueryWrapper<TagRelationEntity> tagRelationWrapper = new QueryWrapper<>();
            tagRelationWrapper.lambda().eq(TagRelationEntity::getEntityId, entity.getId());
            tagRelationService.remove(tagRelationWrapper);

            // 删除关系内容数据
            QueryWrapper<RelationContentEntity> relationContentWrapper = new QueryWrapper<>();
            relationContentWrapper.lambda().eq(RelationContentEntity::getEntityId, entity.getId());
            relationContentService.remove(relationContentWrapper);
        }
        return ActionResult.success("删除成功");
    }

    /**
     * 表单信息(详情页)
     * 详情页面使用-转换数据
     *
     * @param id
     * @return
     */
    @Operation(summary = "表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult detailInfo(@PathVariable("id") String id) {
        // 获取顶层TemplateEntity
        EntityEntity entity = entityService.getInfo(id);
        if (entity == null) {
            return ActionResult.fail("表单数据不存在！");
        }

        // 获取一级关联分类列表(1对多)
        List<EntityCategoryEntity> categories = entityService.getEntityCategoryList(entity.getId());

        // 获取所有属性数据
        List<EntityAttributeEntity> allAttributes = entityService.getEntityAttributeList(entity.getId());

        // 为每个分类设置对应的属性
        categories.forEach(category -> {
            List<EntityAttributeEntity> attributes = allAttributes.stream().filter(attr -> category.getId().equals(attr.getCategoryId())).collect(Collectors.toList());
            category.setEntityAttributeList(attributes);
        });

        // 设置标签和关系
        List<TagVO> tagVOList = tagMangeService.getTagVOList(id);
        List<relationVO> relationVOList = relationMangeService.getRelationVOList(id);
        entity.setTagList(tagVOList);
        entity.setRelationList(relationVOList);

        // 设置分类列表到模板对象
        entity.setEntityCategoryList(categories);

        return ActionResult.success(entity);
    }

    /**
     * 获取详情(编辑页)
     * 编辑页面使用-不转换数据
     *
     * @param id
     * @return
     */
    @Operation(summary = "信息")
    @GetMapping("/{id}")
    public ActionResult info(@PathVariable("id") String id) {
        // 获取顶层TemplateEntity
        EntityEntity entity = entityService.getInfo(id);
        if (entity == null) {
            return ActionResult.fail("表单数据不存在！");
        }

        // 获取一级关联分类列表(1对多)
        List<EntityCategoryEntity> categories = entityService.getEntityCategoryList(entity.getId());

        // 获取所有属性数据
        List<EntityAttributeEntity> allAttributes = entityService.getEntityAttributeList(entity.getId());

        // 为每个分类设置对应的属性
        categories.forEach(category -> {
            List<EntityAttributeEntity> attributes = allAttributes.stream().filter(attr -> category.getId().equals(attr.getCategoryId())).collect(Collectors.toList());
            category.setEntityAttributeList(attributes);
        });


        // 设置标签和关系
        List<TagVO> tagVOList = tagMangeService.getTagVOList(id);
        List<relationVO> relationVOList = relationMangeService.getRelationVOList(id);
        entity.setTagList(tagVOList);
        entity.setRelationList(relationVOList);

        // 设置分类列表到模板对象
        entity.setEntityCategoryList(categories);
        return ActionResult.success(entity);
    }

}
